# -*- coding: utf-8 -*-

from django.shortcuts import render

from django.views import View
# Create your views here.

from .models import *
from utils.pageUtils import *

class IndexView(View):
    #查询所有的类别
    categorys = Category.objects.all()
    #查询第一个类别的id
    current_categoryid = Category.objects.first().id

    def get(self, request, cid=None, pageno=1):

        if cid == None:
            current_cid = self.current_categoryid
        else:
            current_cid = cid
        pages, goods = get_objects_page(Goods.objects.filter(category_id=current_cid), pageno)

        # goods = Goods.objects.filter(category_id=current_cid)
        return render(request, 'index.html',{'categorys': self.categorys, 'current_cid': int(current_cid), 'goods': goods, 'pages': pages})

# 利用装饰器实现推荐商品功能
def wrapper_recommend_goods_cookie(func):
    # 利用装饰器的内部函数,对被装饰的方法进行装饰,所以传入内部函数的参数格式必须与要装饰的函数格式相同
    def _wrapper(detailView, request, gid, *args, **kwargs):
        # 首先我们先从cookies中获取一个名为recommend_goods的字符串内容,内容中是一些经常浏览的商品id
        raw_commend_goods = request.COOKIES.get('recommend_goods','')
        # 然后将该字符串类型的id在列表推导式内部进行一个分割,并且去除每个元素左右的空白字符,最后将分割好的列表赋给一个变量
        commend_goods = [item for item in raw_commend_goods.split() if item.strip()]

        # print commend_goods

        # 自定义算法获取前四个推荐商品
        recommend_goods = [Goods.objects.get(id=c_good) for c_good in commend_goods if c_good != gid and Goods.objects.get(id=gid).category_id == Goods.objects.get(id=c_good).category_id][:4]
        # print recommend_goods
        #调用被装饰的函数获取响应对象,同时将包含着四个商品对象的变量传递进去
        response = func(detailView, request, gid, recommend_goods, *args, **kwargs)

        # 判断商品id是否在commend_goods列表中存在
        # 最新浏览过的商品在最前面显示
        # 如果当前商品id不存在cookies列表中,那就添加到末尾去
        if gid not in commend_goods:
            commend_goods.append(gid)
        else:
            #如果存在,那就删除该id,然后再将其重新插入到COOKIES列表的最前面
            commend_goods.remove(gid)
            commend_goods.insert(0, gid)

        #将推荐商品的id列表按照空格转换为字符串存放至cookie中(单位秒)
        response.set_cookie('recommend_goods',' '.join(commend_goods),max_age=60*60*24*3)

        return response
    return _wrapper


class DetailView(View):
    @wrapper_recommend_goods_cookie
    def get(self,request,gid,recommend_goods):
        goods = Goods.objects.get(pk=int(gid))
        return render(request,'detail.html',{'goods':goods,'recommend_goods':recommend_goods})

